async function processDataSequentially(dataArray, processorFunction) {
    const results = [];
    
    for (const [index, item] of dataArray.entries()) {
        try {
            console.log(`处理第 ${index + 1}/${dataArray.length} 个数据`);
            const result = await processorFunction(item);
            results.push(result);
        } catch (error) {
            console.error(`处理数据 ${item} 时出错:`, error);
            results.push({ error: error.message });
        }
    }
    
    return results;
}

function doAction(oneUrl, resolve) {
    // 打开窗口（处理弹窗被拦截）
const openedWindow = window.open(oneUrl, '_blank');
if (!openedWindow) {
    console.log('窗口被拦截，跳过该条');
    resolve?.();
    return;
}

let attempts = 0;
const maxAttempts = 30; // 最多尝试30次（约60秒，间隔2s）
const tickMs = 2000;
const stopAndResolve = (msg) => {
    if (msg) console.log(msg);
    clearInterval(injectInterval);
    try { if (!openedWindow.closed) openedWindow.close(); } catch (_) {}
    resolve?.();
};

const injectInterval = setInterval(() => {
    attempts++;
    if (openedWindow.closed) {
        stopAndResolve('窗口已关闭，结束定时任务');
        return;
    }
    try {
        console.log('尝试寻找播放按钮');
        const btns = openedWindow.document.getElementsByClassName('dplayer-play-icon');
        if (btns && btns[0]) {
            btns[0].click();
            let mediaElements = Array.from(openedWindow.document.querySelectorAll('video'));
            let playing = mediaElements.filter((element) => !element.paused);
            if (playing.length === 0) {
                console.log('首次点击未播放，重试点击');
                btns[0].click();
            }
            mediaElements = Array.from(openedWindow.document.querySelectorAll('video'));
            playing = mediaElements.filter((element) => !element.paused);
            if (playing.length === 0) {
                stopAndResolve('两次点击仍未播放，结束本条');
                return;
            }
            console.log('检测到正在播放');
            clearInterval(injectInterval);

            const videos = openedWindow.document.getElementsByTagName('video');
            if (videos && videos[0]) {
                // 对 videos[0] 设置倍速
                videos[0].playbackRate = 2;
                videos[0].addEventListener('ended', function () {
                    setTimeout(() => {
                        try { if (!openedWindow.closed) openedWindow.close(); } catch (_) {}
                        resolve?.();
                    }, 1500);
                });
            } else {
                // 未找到 video 标签，直接结束本条
                resolve?.();
            }
        } else {
			// 没有找到播放按钮
			setTimeout(() => {
				try { if (!openedWindow.closed) openedWindow.close(); } catch (_) {}
				resolve?.();
			}, 1500);
		}
    } catch (e) {
        // 跨域：无法访问 openedWindow.document
        if (attempts === 1) console.log('跨域页面，无法注入脚本，需手动播放');
        stopAndResolve('跨域，结束本条');
        return;
    }

    if (attempts >= maxAttempts) {
        stopAndResolve('尝试次数达到上限，结束本条');
    }
}, tickMs);

console.log('已启动 doAction 定时任务');
}


// 使用
var data = [];
var $spanArr = $("span.sh-res-b");
for (var i = 0; i < $spanArr.length; i++) {
    // 必看元素
    var $this =  $($spanArr[i]);
    //if ($this.html() == '(必看)') {
        var $a = $this.parent().find('a');
        // 找到下面的状态，如果是未完成的则需要处理
        var $img = $this.parent().find('img');
        var $imgTitle = $img.attr('title');
        if ($imgTitle == '未看') {
            data.push($a.attr("href"));
            console.log('url==' + $a.attr("href"));
        }
    //}
}

const processor = item => {
    return new Promise((resolve) => {
        var padding = false;
        doAction(item, resolve);
        console.log('结束:processor');
    });
};

processDataSequentially(data, processor).then(results => {
    console.log('最终结果:', results);
});